<?php

/**
 * This is the model class for table "proyecto".
 *
 * The followings are the available columns in table 'proyecto':
 * @property integer $id
 * @property integer $idCoordinador
 * @property string $nombre
 * @property string $objetivo
 * @property integer $finalizado
 *
 * The followings are the available model relations:
 * @property Experimento[] $experimentos
 * @property Usuario $idCoordinador0
 * @property Usuario[] $usuarios
 */
class Proyecto extends CActiveRecord
{
        
        /**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Proyecto the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'proyecto';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('idCoordinador, nombre', 'required'),
			array('idCoordinador, finalizado', 'numerical', 'integerOnly'=>true),
			array('nombre', 'length', 'max'=>255),
			array('objetivo', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, idCoordinador, nombre, objetivo, finalizado', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'experimentos' => array(self::HAS_MANY, 'Experimento', 'idProyecto'),
			'idCoordinador0' => array(self::BELONGS_TO, 'Usuario', 'idCoordinador'),
			'usuarios' => array(self::MANY_MANY, 'Usuario', 'usuarioxproyecto(idProyecto, idUsuario)'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'idCoordinador' => 'Coordinator',
			'nombre' => 'Name',
			'objetivo' => 'Goal',
			'finalizado' => 'Finished',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('idCoordinador',$this->idCoordinador);
		$criteria->compare('nombre',$this->nombre,true);
		$criteria->compare('objetivo',$this->objetivo,true);
		$criteria->compare('finalizado',$this->finalizado);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
        
        /**
        * @return array of valid users for this project, indexed by user IDs
        */
        public function getUserOptions()
        {
            $usersArray = CHtml::listData(Usuario::model()->findAll(), 'id', 'nombre');
            $key = array_search('admin', $usersArray);
            unset($usersArray[$key]);
            $key = array_search('laboratorist', $usersArray);
            unset($usersArray[$key]);
            return $usersArray;
        }
        
        /**
        * @return string the status text display for the current issue
        */
        public function getUserText()
        {
            $userOptions=$this->userOptions;
            return isset($userOptions[$this->idCoordinador]) ?
            $userOptions[$this->idCoordinador] : "unknown status ({$this->idCoordinador})";
        }
        
        public function getFinalizadoText()
        {
            if($this->finalizado)
                return "Si";
            else
                return "No";
        }
        
        public function assignUser($userId, $role)
        {
            $command = Yii::app()->db->createCommand();
            $command->insert('usuarioxproyecto', array(
                        'rol'=>$role,
                        'idUsuario'=>$userId,
                        'idProyecto'=>$this->id,)
            );
        }
        
        public function removeUser($userId)
        {
            $command = Yii::app()->db->createCommand();
            $command->delete(
                'usuarioxproyecto',
                'idUsuario=:userId AND idProyecto=:projectId',
                array(':userId'=>$userId,':projectId'=>$this->id)
            );
        }
        
        public function allowCurrentUser($role)
        {
            $sql = "SELECT * FROM usuarioxproyecto WHERE idProyecto=:projectId AND idUsuario=:userId AND rol=:role";
            $command = Yii::app()->db->createCommand($sql);
            $command->bindValue(":projectId", $this->id, PDO::PARAM_INT);
            $command->bindValue(":userId", Yii::app()->user->getId(), PDO::PARAM_INT);
            $command->bindValue(":role", $role, PDO::PARAM_STR);
            return $command->execute()==1;
        }
        
        /**
        * Returns an array of available roles in which a user can be placed
        when being added to a project
        */
        public static function getUserRoleOptions()
        {
            //return CHtml::listData(Yii::app()->authManager->getRoles(), 'name', 'name');
            $roles=CHtml::listData(Yii::app()->authManager->getRoles(), 'name', 'name');
            $key = array_search('admin', $roles);
            unset($roles[$key]);
            return $roles;
        }
        
        
        /*
        * Determines whether or not a user is already part of a project
        */
        public function isUserInProject($user)
        {
            $sql = "SELECT idUsuario FROM usuarioxproyecto WHERE idProyecto=:projectId AND idUsuario=:userId";
            $command = Yii::app()->db->createCommand($sql);
            $command->bindValue(":projectId", $this->id, PDO::PARAM_INT);
            $command->bindValue(":userId", $user->id, PDO::PARAM_INT);
            return $command->execute()==1;
        }
        
        public function getUserProjects($role)
        {
            $sql = "SELECT u.nombre FROM usuario u, usuarioxproyecto uxp WHERE idProyecto=:projectId AND rol=:role AND u.id=idUsuario";
            $command = Yii::app()->db->createCommand($sql);
            $command->bindValue(":projectId", $this->id, PDO::PARAM_INT);
            $command->bindValue(":role", $role, PDO::PARAM_STR);
            $rows = $command->queryAll();
            $usernames = array();
		foreach($rows as $row)
		{
			$usernames[]=$row['nombre'];
		}
            return $usernames;
        }
        
        
        public static function getUserToProjects()
        {
            $usersArray = CHtml::listData(Usuario::model()->findAll(), 'nombre', 'nombre');
            $key = array_search('admin', $usersArray);
            unset($usersArray[$key]);
            $key = array_search('laboratorist', $usersArray);
            unset($usersArray[$key]);
            return $usersArray;
        }
        
        public function experimentoEnd()
        {
            $sql = "SELECT finalizado FROM experimento WHERE idProyecto=:proyectoId and finalizado=0";
            $command = Yii::app()->db->createCommand($sql);
            $command->bindValue(":proyectoId", $this->id, PDO::PARAM_INT);
            $rows = $command->queryAll();
            foreach($rows as $row)
            {
		if($row['finalizado']==='0')
                    return false;
            }
            return true;
        }
}